<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/04/20
 */
namespace common\tool;

use OSS\Core\OssException;
use OSS\OssClient;
use yii;

class Oss {
    const accessKey = 'LTAIv3FlxHQg6xZr';
    const accessKeySecret = 'frfOuXjVcRzkG9Ab2b4uALOlhSySF2';
    const REGION = 'oss-cn-beijing';
    const DIVE_BUCKET = 'diver-bucket';
    private static $endpoint = "http://oss-cn-beijing.aliyuncs.com";

    public static function upload($url) {
        $object = hash("sha256", $url);
        preg_match('/\.[a-zA-Z]*$/', $url, $match);
        $targetUrl = "http://" . self::DIVE_BUCKET . ".oss-cn-beijing.aliyuncs.com/$object{$match[0]}";
        $endpoint = "http://oss-cn-beijing.aliyuncs.com";
        $content = file_get_contents($url);
        try {
            $ossClient = new OssClient(self::accessKey, self::accessKeySecret, $endpoint);
            $r = $ossClient->putObject(self::DIVE_BUCKET, $object . $match[0], $content);
        } catch (OssException $e) {
            print $e->getMessage();
        }
        return $targetUrl;
    }


    public static function listObjects() {
        try {
            $ossClient = new OssClient(self::accessKey, self::accessKeySecret, self::$endpoint);
            $r = $ossClient->listObjects(self::DIVE_BUCKET);
            var_dump($r);
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }
}
